package com.xujian.flink.join.union;

import com.xujian.common.beans.EventMsg;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author star xu
 * @date 2023/2/1 15:57
 * @Description:
 * @Slogan: 致敬大师,致敬未来的自己
 */
public class UnionExample {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //设置水位线生成周期
//        env.getConfig().setAutoWatermarkInterval(500);

        SingleOutputStreamOperator<EventMsg> stream1 = env.socketTextStream("192.168.16.77",
                        7777)
                .map(data -> {
                    String[] field = data.split(",");
                    return new EventMsg(field[0].trim(), field[1].trim(),
                            Long.valueOf(field[2].trim()));
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<EventMsg>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner((SerializableTimestampAssigner<EventMsg>) (element, recordTimestamp) -> element.timestamp)
                );
        stream1.print("stream1");
        SingleOutputStreamOperator<EventMsg> stream2 =
                env.socketTextStream("192.168.16.78", 7777)
                        .map(data -> {
                            String[] field = data.split(",");
                            return new EventMsg(field[0].trim(), field[1].trim(),
                                    Long.valueOf(field[2].trim()));
                        })
                        .assignTimestampsAndWatermarks(WatermarkStrategy.<EventMsg>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((SerializableTimestampAssigner<EventMsg>) (element, recordTimestamp) -> element.timestamp)
                        );
        stream2.print("stream2");
        // 合并两条流
        stream1.union(stream2)
                .process(new ProcessFunction<EventMsg, String>() {
                    @Override
                    public void processElement(EventMsg value, Context ctx,
                                               Collector<String> out) throws Exception {
                        out.collect(" 水 位 线 ： " +
                                ctx.timerService().currentWatermark());
                    }
                })
                .print();
        env.execute();
    }
}
